const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:0,
    banner: '/banner2.gif',
    banner1: '/banner3.gif',
    banner2: '/banner10.gif',
    item: [ "非定向", "助学", "助医", "助老", "助残", "助困", "助益"],
    hideBox: ["否", "是"],
    moneys: [10, 30, 50],
    name: '',
    phone: '',
    msg: '',
    index: 0,
    selectIndex: -1,
    reallyMoney: 0,
    money: '',
    isHide: 0,
    disabled: false,
    saveStatus:false
  },
  toInput: function (e) {
    console.log(e);
    if (e.detail.value.length > 0) {
      this.setData({
        selectIndex: -1,
        reallyMoney: parseFloat(e.detail.value)
      });
    } else {
      this.setData({
        selectIndex: -1,
        reallyMoney: 0
      });
    }
  },
  sybtn: function (e) {
    var money = [3.33, 6.88, 8.88, 9.99, 13.88, 16.88, 18.88, 23.88, 28.88, 33.33, 38.88];
    var random = parseInt(Math.random() * money.length);
    var self = this.setData({
      selectIndex: -1,
      reallyMoney: money[random],
      money: money[random]
    });
  },
  selectHide: function (e) {
    var index = parseInt(e.target.dataset.index);
    this.setData({
      isHide: index
    });
  },
  selectMoney: function (e) {
    var index = parseInt(e.target.dataset.index);
    var reallyMoney = parseInt(e.target.dataset.money);
    this.setData({
      selectIndex: index,
      reallyMoney: reallyMoney,
      money: ''
    });
  },
  bindChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;
    var word = ["慈善是一盏灯：温暖别人，照亮自己。", "送出一份真情，奉献一份爱心。", "汇小流成大海，积小善成大德。"];
    var random = parseInt(Math.random() * word.length);

    that.setData({
      msg: word[random],
      status: options.status,
      bnStatus:options.bnStatus,
      id: options.id,
      baseUrl: app.globalData.baseUrl,
    });

    if (options.status == 1) {
      wx.request({
        url: app.globalData.baseUrl + '/api/index/getCishanList?id=' + options.id,
        header: {
          'content-type': 'application/json'
        },
        success: res => {
          that.setData({
            bTitle: res.data.data[0].title,
            disabled: true
          })
        }
      })
    } else if (options.status == 2) {
      wx.request({
        url: app.globalData.baseUrl + '/api/index/getDingxiangList?id=' + options.id,
        header: {
          'content-type': 'application/json'
        },
        success: res => {
          console.log(res.data.data)
          that.setData({
            bTitle: res.data.data[0].title,
            disabled: true
          })
        }
      })
    } else if (options.status == 4) {

      that.setData({
        id: 0
      });

    }




    var openid = wx.getStorageSync("openid");
    var userInfo = wx.getStorageSync("userInfo");
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    if (openid != '') {
      this.setData({
        hasUserInfo: true,
        userInfo: userInfo
      })
    };
  },
  submitData: function (e) {
    //console.log(e);
    var data = e.detail.value;
    var reallyMoney = this.data.reallyMoney;
    if (data.item == "") {
      wx.showToast({
        title: '请先选择支持的项目',
        icon: 'none',
        duration: 1500
      })
    } else if (reallyMoney < 0 || reallyMoney == "") {
      wx.showToast({
        title: '请先选择或输入捐助金额',
        icon: 'none',
        duration: 1500
      })
    } else if (this.data.isHide == 0) {

      if (data.name == '') {
        this.setData({
          name:this.data.userInfo.nickName
        })
        // wx.showToast({
        //   title: '请输入姓名',
        //   icon: 'none',
        //   duration: 2000
        // });
        // return false;
      } else {
        this.setData({
          name: data.name
        })
      }
      if (!(/^1[345678]\d{9}$/.test(data.phone)) && data.phone != '') {
        wx.showToast({
          title: '电话格式不正确',
          icon: 'none',
          duration: 2000
        });
        return false;
      }
      
    } else {

      if (this.data.isHide == 1) {
        this.setData({
          name: '匿名',
          title: data.item,
        })
      }
      
    }

    if (this.data.id==0) {
      this.bindPay(reallyMoney, this.data.status, this.data.index, this.data.name, data.phone, data.msg, this.data.isHide);
    }else{
      this.bindPay(reallyMoney, this.data.status, this.data.id, this.data.name, data.phone, data.msg, this.data.isHide);
    }

    
    var word = ["慈善是一盏灯：温暖别人，照亮自己。", "送出一份真情，奉献一份爱心。", "汇小流成大海，积小善成大德。"];
    var random = parseInt(Math.random() * word.length);

  },
  bindPay(price, donate_type, donate_type_id, name, mobi, info, is_hidden) {
    var openid = wx.getStorageSync("openid");
    var that = this;
    wx.request({
      url: app.globalData.baseUrl + '/api/index/Pay',
      data: {
        openid: openid,
        nickname: that.data.userInfo.nickName,
        headimg: that.data.userInfo.avatarUrl,
        price: price,
        donate_type: donate_type,
        donate_type_id: donate_type_id,
        name: name,
        mobi: mobi,
        info: info,
        is_hidden: is_hidden
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: "POST",
      success: function (res) {
        console.log(res.data.payMap);
        that.doWxPay(res.data.payMap);
      },
      fail: function (err) {
        wx.showToast({
          icon: "none",
          title: '服务器异常，清稍候再试'
        })
      },
    });
  },

  doWxPay(param) {
    var that = this;
    //小程序发起微信支付
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: 'MD5',
      paySign: param.paySign,
      success: function (event) {
        // success
        console.log(event);
        var date = new Date();
        var time = date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日';
        if (that.data.status == 4) {
          that.saveImg(that.data.name, that.data.item[that.data.index], time, that.data.reallyMoney);
        } else {
          that.saveImg(that.data.name, that.data.bTitle, time, that.data.reallyMoney);
        }

        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });
      },

      fail: function (error) {
        console.log("支付失败")
        console.log(error)
      },
      complete: function () {
        console.log("pay complete")
      }
    });

  },
  saveImg: function (name1, title1, time, money) {
    wx.showLoading({
      title: '合成海报中',
    });
    var that = this;
    that.setData({
      saveStatus:true
    })
    var userInfo = that.data.userInfo;
    var context = wx.createCanvasContext('mycanvas', that);
    context.setFillStyle("#ffe200")
    context.fillRect(0, 0, 640, 945)
    var path1 = userInfo.avatarUrl;
    var path2 = "https://donate.kyhdmedia.com/static/uploads/app/post1.png";
    var path3 = "https://donate.kyhdmedia.com/static/uploads/app/er.png";
    let promise1 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: path1,
        success: function (res) {
          resolve(res.path);
        }
      })
    });
    let promise2 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: path2,
        success: function (res) {
          resolve(res.path);
        }
      })
    });
    let promise3 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: path3,
        success: function (res) {
          resolve(res.path);
        }
      })
    });

    Promise.all([promise1, promise2, promise3]).then(res => {
      context.drawImage(res[0], 265, 304, 114, 114);
      context.drawImage(res[1], 0, 0, 640, 945);
      context.drawImage(res[2], 50, 722, 136, 134);
      var name = '亲爱的' + name1;
      var l = 0;
      var title = "";
      for (var i = 0; i < name.length; i++) {
        var reg = /^[\u4E00-\u9FA5]+$/;
        var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
        if (reg.test(name[i]) || reg1.test(name[i])) {
          l += 2;
        } else {
          l += 1;
        }
        if (l > 40) {
          title = name.substring(0, i - 1) + '...';
          break;
        }
      }
      if (l <= 40) {
        title = name;
      }
      context.setFillStyle('#4d2600');
      context.setFontSize(24);
      context.fillText(title, 70, 480);

      // context.
      context.setTextAlign('left');
      var l = 0;
      var j = 0;
      var k = 0;
      var lg = [36, 42, 42, 42, 42];
      var txt = [];
      var yes = false;
      var word = '感谢您于' + time + '向佛山市顺德区龙江慈善会的' + title1 + '捐款￥' + money + '元。我们将遵照您的意愿，全部用于公益慈善事业。对于您的善行义举，致以诚挚的敬意。';
      for (var i = 0; i < word.length; i++) {
        var reg = /^[\u4E00-\u9FA5]+$/;
        var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
        var add = 0;
        if (reg.test(word[i]) || reg1.test(word[i])) {
          add = 2;
        } else {
          add = 1;
        }
        l += add;
        if (l == lg[k]) {
          txt.push(word.substring(j, i + 1));
          console.log(i);
          j = i + 1;
          l = 0;
          k++;
          yes = true;
        } else if (l > lg[k]) {
          txt.push(word.substring(j, i));
          j = i;
          l = add;
          yes = true;
          k++;
        } else if (i == word.length - 1) {
          if (l < lg[k]) {
            k++;
            txt.push(word.substring(j, word.length));
          }
        }
      }
      console.log(txt);
      var xx = [120, 70, 70, 70, 70];
      var yy = [530, 575, 620, 665, 710];
      for (var i = 0; i < txt.length; i++) {
        context.fillText(txt[i], xx[i], yy[i], 508);
      }
      context.setTextAlign('left');
      var company = '佛山市顺德区龙江慈善会';
      context.fillText(company, 574 - context.measureText(company).width, 774);
      context.fillText(time, 574 - context.measureText(time).width, 816);
      context.draw();
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          fileType: 'png',
          destWidth: 640,
          destHeight: 945,
          success: function (res) {
            var tempFilePath = res.tempFilePath;
            console.log(tempFilePath);
            wx.hideLoading();
            that.setData({
              imagePath: tempFilePath,
              pops: true,
              saveStatus:false
            });
          },
          fail: function (res) {
            console.log(res);
          }
        })
      }, 2000);
    })
  },
  // saveImg:function(name1,title1,time,money){
  //   wx.showLoading({
  //     title: '合成海报中',
  //   })
  //   var that  = this;
  //   var userInfo = that.data.userInfo;
  //   var context = wx.createCanvasContext('mycanvas',that);
  //   context.setFillStyle("#ffe200")
  //   context.fillRect(0, 0, 640, 1138)
  //   var path1 = userInfo.avatarUrl;
  //   var path2 = "https://donate.kyhdmedia.com/static/uploads/app/post2.png";
  //   var path3 = "https://donate.kyhdmedia.com/static/uploads/app/er.png";
  //   let promise1 = new Promise(function(resolve, reject) {
  //     wx.getImageInfo({
  //       src: path1,
  //       success: function(res) {
  //         resolve(res.path);
  //       }
  //     })
  //   });
  //   let promise2 = new Promise(function(resolve, reject) {
  //     wx.getImageInfo({
  //       src: path2,
  //       success: function(res) {
  //         resolve(res.path);
  //       }
  //     })
  //   });
  //   let promise3 = new Promise(function(resolve, reject) {
  //     wx.getImageInfo({
  //       src: path3,
  //       success: function(res) {
  //         resolve(res.path);
  //       }
  //     })
  //   });

  //   Promise.all([promise1,promise2,promise3]).then(res=>{
  //     context.drawImage(res[0], 241,227, 163, 163);
  //     context.drawImage(res[1], 0, 0, 640, 1138);
  //     context.drawImage(res[2], 98, 881, 136, 134);
  //     var name = '亲爱的'+name1;
  //     var l = 0;
  //     var title = "";
  //     for(var i=0; i<name.length; i++)
  //     {
  //       var reg=/^[\u4E00-\u9FA5]+$/;
  //       var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
  //       if(reg.test(name[i])||reg1.test(name[i]))
  //       {
  //         l+=2;
  //       }else{
  //         l+=1;
  //       }
  //       if(l>40)
  //       {
  //         title = name.substring(0,i-1)+'...';
  //         break;
  //       }
  //     }
  //     if(l<=40){
  //       title = name;
  //     }
  //     context.setFillStyle('#4d2600');
  //     context.setFontSize(24);
  //     context.fillText(title,118, 480);

  //     // context.
  //     context.setTextAlign('left');  
  //     var l = 0;
  //     var j = 0;
  //     var k = 0;
  //     var lg = [32,37,37,37,37];
  //     var txt = [];
  //     var yes = false;
  //     var word = '感谢您于'+time+'向佛山市顺德区龙江慈善会的'+title1+'捐款￥'+money+'元。我们将遵照您的意愿，全部用于公益慈善事业。对于您的善行义举，致以诚挚的敬意。';
  //     for(var i=0; i<word.length; i++)
  //     {
  //       var reg=/^[\u4E00-\u9FA5]+$/;
  //       var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
  //       var add = 0;
  //       if(reg.test(word[i])||reg1.test(word[i]))
  //       {
  //         add=2;
  //       }else{
  //         add=1;
  //       }
  //       l+=add;
  //       if(l==lg[k])
  //       {
  //         txt.push(word.substring(j,i+1));
  //         console.log(i);
  //         j = i+1;
  //         l = 0;
  //         k++;
  //         yes = true;
  //       }else if(l>lg[k])
  //       {
  //         txt.push(word.substring(j,i));
  //         j = i;
  //         l = add;	
  //         yes = true;
  //         k++;
  //       }else if(i==word.length-1)
  //       {
  //         if(l<lg[k])
  //         {
  //           k++;
  //           txt.push(word.substring(j,word.length));
  //         }
  //       }
  //     }
  //     console.log(txt);  
  //     var xx  = [168,118,118,118,118,118];
  //     var yy  = [540,585,630,675,720,765];
  //     for(var i=0; i<txt.length; i++)
  //     {
  //       context.fillText(txt[i],xx[i], yy[i],508);
  //     }
  //     context.setTextAlign('left');  
  //     var company = '佛山市顺德区龙江慈善会';
  //     context.fillText(company,574-context.measureText(company).width,774);
  //     context.fillText(time,574-context.measureText(time).width,816);
  //     context.draw();
  //     setTimeout(function () {
  //       wx.canvasToTempFilePath({
  //         canvasId: 'mycanvas',
  //         fileType: 'png',
  //         destWidth: 640,
  //         destHeight: 1138,
  //         success: function (res) {
  //           var tempFilePath = res.tempFilePath;
  //           console.log(tempFilePath);
  //           wx.hideLoading();
  //           that.setData({
  //             imagePath: tempFilePath,
  //             pops:true
  //           });
  //         },
  //         fail: function (res) {
  //           console.log(res);
  //         }
  //       })  
  //     }, 2000);
  //   })
  // },
  confrimPop: function () {
    this.setData({
      pops: false
    });
  },
  downImg(e) {
    console.log(1);
    var self = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              wx.saveImageToPhotosAlbum({
                filePath: self.data.imagePath,
                success: function (data) {
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
              })
            },
            fail() {
              wx.showModal({
                title: "qing信息失败",
                content: "请允许授权以便为您提供给服务",
                success: function (e) {
                  e.confirm && this.getUserProfile();
                }
              });
            },
          })
        } else {
          wx.saveImageToPhotosAlbum({
            filePath: self.data.imagePath,
            success: function (data) {
              wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              })
            }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: '和善龙江 随缘乐捐',
      path:'/pages/index/index',
       imageUrl: 'http://cdn2.kyhdmedia.com/xcx_ljcs/share.jpg'
    }
  },
  onShareTimeline: function () {
    var that = this;
    return {
      title: '和善龙江 随缘乐捐',
      path:'/pages/main/main',
       imageUrl: 'http://cdn2.kyhdmedia.com/xcx_ljcs/share.jpg'
    }
  }
})